<script>
import _ from "lodash";
import { h } from "vue";
import {
  addResizeListener,
  removeResizeListener
} from '../../tools/resize-event'

const emptyColumnConfig = (item) => {
  return {
    maxWidth: undefined,
    colNum: 2, // 24
    gutter: 0,
    ...(item || {})
  }
}


export default {
  componentName: "CGGird",
  name: "cg-gird",
  props: {
    data: Array,
    column: Object,
    shape: String
  },
  data() {
    return {
      width: 0,
      container: undefined,
      itemList: [],
      updateWidth: undefined,
      viewVisible: false
    }
  },
  computed: {
    columnConfig() {
      return emptyColumnConfig(this.column)
    }
  },
  created() {
    this.updateWidth = _.debounce(() => {
      console.log("updateWidth")
      if (this.container instanceof Element) {
        const rect = this.container.getBoundingClientRect()
        this.width = rect.width;
        this.itemList.forEach(item => item.updateGirdItemStyle())
        this.viewVisible = true
      }
    }, 20)
  },
  mounted() {
    this.container = this.$refs["container"];
    if (this.container) {
      addResizeListener(this.container, this.updateWidth);
    }
  },
  unmounted() {
    if (this.container) {
      removeResizeListener(this.container, this.updateWidth);
    }
  },
  methods: {
    addItem(node) {
      this.itemList.push(node)
      this.updateWidth()
    },
    removeItem(node) {
      _.remove(this.itemList, (item) => item.girdItemId === node.girdItemId)
      this.updateWidth()
    }
  },
  render() {
    return h("div", {
      class: "cg-gird", ref: "container", style: {
        opacity: this.viewVisible ? 1 : 0
      }
    }, [
      h(this.$slots.default)
    ])
  }
}

</script>

<style lang="scss">
@use "./style.scss";
</style>